module vfs.recentcollector;

import vfs.jsonreader;
import vfs.jsonwriter;
import utils.log;

import std.file;
import std.stream: OpenException;

class RecentCollector {
    private const string FILE_NAME = "config/recent.json";
    private shared string[] myRecentProjects;
    private static shared RecentCollector ourInstance;

    static this() {
        ourInstance = new shared(RecentCollector());
    }

    private this() {
        myRecentProjects = new shared(string)[0];
        auto jsonReader = new shared(JSONReader)(FILE_NAME);
        try {
            jsonReader.read((JSONValue v) {
                if (v.type != JSON_TYPE.ARRAY) {
                    Log.message(format("Wrong format in file %s", FILE_NAME));
                    return;
                }
                foreach (element; v.array) {
                    if (element.type != JSON_TYPE.STRING) {
                        Log.message(format("Wrong record type in %s", FILE_NAME));
                        continue;
                    }
                    string path = element.str;
                    if (!exists(path)) {
                        Log.message(format("Wrong filename: %s in %s", path, FILE_NAME));
                        continue;
                    }
                    myRecentProjects ~= path;
                }
            });
        } catch (OpenException e) {
            Log.message("There is no recent projects");
        }
    }

    public static shared(RecentCollector) getInstance() shared {
        return ourInstance;
    }

    public shared(string)[] getRecentProjectsList() shared {
        return myRecentProjects;
    }

    private ~this() {
        debug Log.message("RecentCollector dtor called");
        if (myRecentProjects.length != 0) {
            JSONValue[] array = new JSONValue[myRecentProjects.length];
            foreach (i, p; myRecentProjects) {
                array[i].type = JSON_TYPE.STRING;
                array[i].str = p;
            }
            JSONValue root;
            root.type = JSON_TYPE.ARRAY;
            root.array = array;
            (new shared(JSONWriter)(FILE_NAME)).write(root);
        }
    }
}
